package com.lagou.edu.course.remote;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthRequest;
import com.aliyuncs.vod.model.v20170321.GetVideoPlayAuthResponse;
import com.lagou.edu.common.util.ConverUtil;
import com.lagou.edu.course.api.dto.MediaDTO;
import com.lagou.edu.course.api.dto.VideoPlayDto;
import com.lagou.edu.course.entity.Lesson;
import com.lagou.edu.course.entity.Media;
import com.lagou.edu.course.service.ILessonService;
import com.lagou.edu.course.service.IMediaService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * TODO
 *
 * @author lm
 * @since 2021/11/1 9:22
 */
@Slf4j
@Service
public class MediaService {
    @Autowired
    IMediaService iMediaService;

    @Autowired
    ILessonService iLessonService;

    DefaultAcsClient aliClient = null;

    public MediaDTO getMediaByLessonId(Integer lessonId) {
        Media media = iMediaService.lambdaQuery().eq(Media::getLessonId, lessonId).one();
        return ConverUtil.convert(media, MediaDTO.class);
    }

    public void updateOrSaveMedia(MediaDTO mediaDTO) {
        Media media = new Media();
        BeanUtils.copyProperties(mediaDTO, media);
        Integer lessonId = mediaDTO.getLessonId();
        Lesson lesson = iLessonService.getById(lessonId);
        if (lesson == null) {
            log.error("没有对应的lesson信息 mediaDTO:{}", JSON.toJSONString(mediaDTO));
            return;
        }
        //lesson.setDuration(media.getDurationNum() / 60);
        iLessonService.saveOrUpdate(lesson);

        Integer courseId = lesson.getCourseId();
        Integer sectionId = lesson.getSectionId();
        media.setCourseId(courseId);
        media.setSectionId(sectionId);

        List<Media> mediaList = iMediaService.lambdaQuery()
                .eq(Media::getLessonId, lessonId)
                .eq(Media::getCourseId, courseId)
                .eq(Media::getSectionId, sectionId)
                .eq(Media::getIsDel, Boolean.FALSE)
                .list();

        if (!CollectionUtils.isEmpty(mediaList)) {
            Integer id = mediaList.get(0).getId();
            media.setId(id);
        } else {
            media.setCreateTime(LocalDateTime.now());
        }
        media.setUpdateTime(LocalDateTime.now());
        iMediaService.saveOrUpdate(media);
    }


    public VideoPlayDto getVideoPlayInfo(Integer lessonId, Integer userId) {
        MediaDTO mediaDTO = getMediaByLessonId(lessonId);
        if (mediaDTO == null) {
            log.info("对应的课时视频不存在,lessonId={},userId={}", lessonId, userId);
            return null;
        }
        //获取阿里云视频播放的必要信息
        String fileId = mediaDTO.getFileId();

        VideoPlayDto aliYunVideoPlayInfo = new VideoPlayDto();
        try {
            String playAuth = getAliVideoPlayAuth(fileId);
            aliYunVideoPlayInfo.setPlayAuth(playAuth);
        } catch (com.aliyuncs.exceptions.ClientException e) {
            log.info("获取阿里云视频播放PlayAuth出错！", e);
            return null;
        }

        aliYunVideoPlayInfo.setFileId(fileId);
        Lesson lesson = iLessonService.getById(lessonId);


        if (lesson.getIsFree()) {
            log.info("对应的课时视频免费,lessonId={},userId={}", lessonId, userId);
            return aliYunVideoPlayInfo;
        }

        if (userId == null) {
            log.info("用户ID为空,lessonId={},userId={}", lessonId, userId);
            return null;
        }

        Integer courseId = lesson.getCourseId();
        if (courseId == null) {
            log.info("课时媒体资源对应的课程ID为空, fileId:{}，userId:{}", fileId, userId);
            return null;
        }
        //ResponseDTO<Integer> responseDTO = userCourseOrderRemoteService.countUserCourseOrderByCoursIds(userId, Arrays.asList(courseId));
//        if (responseDTO.isSuccess() && responseDTO.getContent().compareTo(0) > 0) {
//            return aliYunVideoPlayInfo;
//        }

        return aliYunVideoPlayInfo;
        //return null;
    }

    /**
     * 查询阿里auth
     *
     * @param vid
     * @return
     * @throws
     */
    public String getAliVideoPlayAuth(String vid) throws com.aliyuncs.exceptions.ClientException {
        GetVideoPlayAuthRequest playAuthRequest = new GetVideoPlayAuthRequest();
        playAuthRequest.setVideoId(vid);
        GetVideoPlayAuthResponse acsResponse = getAliVodClient().getAcsResponse(playAuthRequest);
        return acsResponse.getPlayAuth();
    }

    protected DefaultAcsClient getAliVodClient() {
        if (aliClient != null) {
            return aliClient;
        }
        // 点播服务接入区域
        String regionId = "cn-shanghai";
        DefaultProfile profile = DefaultProfile.getProfile(regionId, "LTAI5tALs6YpaWYXftbCYvY8", "ckjnGs6TWtYPJCQqUC1rTr65VmpBDS");
        aliClient = new DefaultAcsClient(profile);
        return aliClient;
    }

}
